import _ from 'lodash';
import { queryRate,  queryRateList} from '@src/api/TaskApi.ts';
import i18n from '@src/locales'
import MathUtil from '@src/util/math';
const TASK_RECEIPT = {
  name: 'task-receipt-mixin',
  props: {
    totalCurrency: {
      type: String,
      default: ''
    },
    
  },
  methods: {
    // 汇率换算方式修改
    exchangeMethodChange(value, index) {
      if(value.exchangeMethod == 1) {
        this.setCurrenyKey(value, value.salePriceCurrency || 'CNY' )
      }else {
        let manualCurrencyObj = JSON.parse(localStorage.getItem(`set_manual_curreny_${this.taskId}`)) || {}
        let exchangeRate = manualCurrencyObj[value.salePriceCurrency] || ''
        this.$set(value, 'exchangeRate', exchangeRate)
      }
    },
    // 单价货币修改
    salePriceCurrencyChange(value) {
      // 如果汇率换算方式不是手填（可能为空或者1），需要给一个默认值1
      // 如果单价货币和结算货币不一致才调用接口，一样则直接设置成1，不需要调汇率接口
      if((value.salePriceCurrency == this.totalCurrency) ) {
        this.$set(value, 'exchangeRate', 1)
      }else {
        if(value.exchangeMethod !==2) {
          this.$set(value, 'exchangeMethod', 1)
          this.setCurrenyKey(value, value.salePriceCurrency || 'CNY')
        }else {
          // 将最新的手填汇率缓存
          let manualCurrencyObj = JSON.parse(localStorage.getItem(`set_manual_curreny_${this.taskId}`)) || {}
          if(!manualCurrencyObj[value.salePriceCurrency]) {
            manualCurrencyObj[value.salePriceCurrency] = ''
          }
          this.$set(value, 'exchangeRate', manualCurrencyObj[value.salePriceCurrency])
          localStorage.setItem(`set_manual_curreny_${this.taskId}`, JSON.stringify(manualCurrencyObj))
        }
      }
    },
    // 获取单个汇率
    async setCurrenyKey(value, source='CNY') {
      let currencyObj = JSON.parse(localStorage.getItem(`set_curreny_key_${this.taskId}`)) || {}
      let index = Object.keys(currencyObj).findIndex(item => item == source)
      if(index < 0 ) {
        let { status, data } = await queryRate({source, target: this.totalCurrency})
        if(status !== 0)  return this.$platform.alert(i18n.t('common.currency.queryException'));
        currencyObj[source] = data
        localStorage.setItem(`set_curreny_key_${this.taskId}`, JSON.stringify(currencyObj))
      }
      this.$set(value, 'exchangeRate', currencyObj[source])
    },
    // 手写汇率缓存
    exchangeRateChange(item) {
      let value = item.exchangeRate
      let count = MathUtil.decimalNumber(value);
      if (value <= 0 || value > 100000000) {
        this.$platform.alert(i18n.t('common.currency.exchangeRateLimit1'));
        item.exchangeRate = ''
        return;
      }
      if(count > 6) {
        this.$platform.alert(i18n.t('common.currency.exchangeRateLimit1'));
        item.exchangeRate = ''
        return;
      }
      if(item.exchangeMethod == 2) {
        // 先获取最新的缓存再存入新的key
        let manualCurrencyObj = JSON.parse(localStorage.getItem(`set_manual_curreny_${this.taskId}`)) || {}
        let salePriceCurrency = item.salePriceCurrency || 'CNY'
        manualCurrencyObj[salePriceCurrency] = value
        localStorage.setItem(`set_manual_curreny_${this.taskId}`, JSON.stringify(manualCurrencyObj))
      }
    },
    // 切换结算币种汇率需要重新从接口获取并缓存
    changeCurrencyType(exchangeRateObj) {
      let newValue = this.value;
      newValue.forEach(item => {
        let salePriceCurrency = item.salePriceCurrency || 'CNY'
        if(item.exchangeMethod !== 2) {
          this.$set(item, 'exchangeMethod', 1)
          this.$set(item, 'exchangeRate', exchangeRateObj[salePriceCurrency])
        }else {
          if((salePriceCurrency == this.totalCurrency) ) {
            this.$set(item, 'exchangeRate', 1)
          } else {
            let manualCurrencyObj = JSON.parse(localStorage.getItem(`set_manual_curreny_${this.taskId}`)) || {}
            this.$set(item, 'exchangeRate', manualCurrencyObj[salePriceCurrency])
          }
        }
      })
      this.$emit('update', {field: this.field, newValue});
    },
    stagingCurrencyType() {
      // this.value有值说明是编辑情况，需要先将上次的汇率数据进行缓存，手填汇率和银行汇率需要存两份
      if(this.value?.length > 0 ){
        this.value.forEach(item => {
          let currencyObj = JSON.parse(localStorage.getItem(`set_curreny_key_${this.taskId}`)) || {}
          let manualCurrencyObj = JSON.parse(localStorage.getItem(`set_manual_curreny_${this.taskId}`)) || {}
          let salePriceCurrency = item.salePriceCurrency || 'CNY'
          if(item.exchangeMethod != 2) {
            currencyObj[salePriceCurrency] = item.exchangeRate
            localStorage.setItem(`set_curreny_key_${this.taskId}`, JSON.stringify(currencyObj))
          }else {
            manualCurrencyObj[salePriceCurrency] = item.exchangeRate
            localStorage.setItem(`set_manual_curreny_${this.taskId}`, JSON.stringify(manualCurrencyObj))
          }
        })
      }
    },

    // 批量添加方法
    async getCurrenyKeyArr(data, target='CNY') {
      let currencyObj = JSON.parse(localStorage.getItem(`set_curreny_key_${this.taskId}`)) || {}
      let currencyType = []
      data.forEach(item => {
        let salePriceCurrency = item.salePriceCurrency || 'CNY'
        let index = Object.keys(currencyObj).findIndex(items => items == salePriceCurrency)
        if(index < 0 && !(currencyType.includes(salePriceCurrency))) {
          currencyType.push(salePriceCurrency)
        }
      })
      let exchangeRateObj = {}
      if(currencyType.length > 0) {
        let { status, data } = await queryRateList({sourceList: currencyType, target})
        if(status !== 0) return this.$platform.alert(i18n.t('common.currency.queryException'));
        exchangeRateObj = data.result
      }
      let currencyObjResult = { ...exchangeRateObj, ...currencyObj}
      localStorage.setItem(`set_curreny_key_${this.taskId}`, JSON.stringify(currencyObjResult))
      return currencyObjResult
    },
  },
  mounted(){
    this.$eventBus.$on('task_receipt_update_currency-type', this.changeCurrencyType);
    this.stagingCurrencyType()
  },
  beforeDestroy() {
    // 关闭弹窗缓存清除
    localStorage.removeItem(`set_curreny_key_${this.taskId}`)
    localStorage.removeItem(`set_manual_curreny_${this.taskId}`)
  },
  destroyed(){
    
  }
};

export default TASK_RECEIPT;
